package com.nimnaw.android.flashlight;

import java.util.List;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;

public class MainActivity extends Activity {
	private boolean supportTorch;
	private Camera camera;

	private ToggleButton button;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		camera = Camera.open();
		if (camera != null) {

			List<String> supportedFlashModes = camera.getParameters()
					.getSupportedFlashModes();
			supportTorch = supportedFlashModes != null
					&& supportedFlashModes
							.contains(Parameters.FLASH_MODE_TORCH);

			if (supportTorch) {
				button = (ToggleButton) this.findViewById(R.id.button_switch);
				button.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						if (camera != null) {
							turnOff();
						} else {
							turnOn();
						}
					}
				});
			}

			camera.release();
			camera = null;
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		turnOn();
	}

	@Override
	protected void onStop() {
		super.onStop();
		turnOff();
	}

	private void turnOn() {
		camera = Camera.open();
		Parameters parameters = camera.getParameters();
		parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
		camera.setParameters(parameters);

		button.setChecked(true);
	}

	private void turnOff() {
		if (camera != null) {
			Parameters parameters = camera.getParameters();
			parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
			camera.setParameters(parameters);
			camera.release();
			camera = null;
		}

		button.setChecked(false);
	}
}
